#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for recv() and send() */
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>     /* for close() */

#include "Header.h"

#define BUFSIZE 1024   /* Size of receive buffer */

void DieWithError(char *errorMessage);  /* Error handling function */

void HandleTCPClient(const char *addr, int clntSocket) {
  int recvFileSize = 0;
  file_header h;
  FILE *fp;
  int oldSize = 0;

	memset(&h, 0, sizeof(h));
	if(recv(clntSocket, &h, sizeof(h), 0) < 0)
		DieWithError("recv() failed");

	printf("length : %d\n", h.len);

    if(access(h.filename, F_OK) < 0) {
        oldSize = oldSize;
    } else {
        struct stat fst;
        memset(&fst, 0, sizeof(fst));
        stat(h.filename, &fst);
//        oldSize = htonl(fst.st_size);
        oldSize = fst.st_size;
    }
    recvFileSize += oldSize;
    send(clntSocket, &oldSize, sizeof(oldSize), 0);

	if((fp = fopen(h.filename, "a")) != 0) {
        int origFileSize = h.len;
		char buf[BUFSIZE];
		
		printf("File Writing Start\n");
		while(origFileSize > recvFileSize) {
			int len;

			memset(buf, 0, sizeof(buf));
			len = recv(clntSocket, buf, BUFSIZE, 0);
			printf("recv file size : %d\n", len);
			fwrite(buf, sizeof(char), len, fp);
			recvFileSize += len;
		}
		printf("File Writing End\n");

		fclose(fp);

        chmod(h.filename, h.perm);
        chown(h.filename, h.uid, h.gid);
	}

    close(clntSocket);    /* Close client socket */
} 
